package com.kindsoft.demo.web.controller;

import com.kindsoft.demo.dao.LdapUserDao;
import com.kindsoft.demo.ldap.UserDao;
import com.kindsoft.demo.services.ADUserService;
import com.kindsoft.demo.services.LdapService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.ldap.filter.AndFilter;
import org.springframework.ldap.filter.EqualsFilter;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Created by zhoujm on 2020/2/19/019.
 */
@RestController
@RequestMapping("ldap")
public class LdapController {

    private final Logger log = LoggerFactory.getLogger(getClass());

    @Value("${ldap.base}")
    private String ldapBaseDn;

    @Autowired
    LdapService ldapService;

    @Autowired
    ADUserService adUserService;

    @Autowired
    UserDao userDao;

    @Autowired
    LdapUserDao ldapUserDao;


    @GetMapping("test")
    public String test(){
        adUserService.getUserNames();
        AndFilter filter = new AndFilter();
        filter.and(new EqualsFilter("objectClass", "person"));
//        ldapService.getDepartmentList("ou=People,dc=seecent,dc=com", filter);
        ldapService.getDepartmentList("", filter);
        return "i love java";
    }

    @GetMapping("change")
    public String change(){
//        ldapService.create("sky", "uid=sky,ou=People");
//        ldapService.search("person");
//        ldapService.update("uid=sky,ou=People");
        try {
            log.info("<change> skyuser");
            ldapService.create("sky", "skyuser");
            ldapService.search("user");
            ldapService.update("CN=skyuser,CN=Users");
        } catch (Exception e) {
            log.error("<change> error: " + e.getMessage(), e);
        }

        return "i love java";
    }

    @GetMapping("users")
    public String users(){
        ldapUserDao.findAll().forEach(u -> {
            log.info("<users> u=" + u);
        });
        return "i love java";
    }

    @GetMapping("adUsers")
    public String adUsers(){
        userDao.findAll().forEach(p -> {
            log.info("<adUsers> p=" + p);
        });
        return "i love java";
    }

    @GetMapping("auth")
    public String auth(){
        if (ldapBaseDn.contains("seecent")) {
            ldapService.authenticate("Manager", "secret");
        } else {
            ldapService.authenticate("adminstrator", "Kindsoft@123");
        }
        return "i love java";
    }
}
